using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using SeataNet.Core.Common;
using SeataNet.Core.RPC;
using SeataNet.Core.Monitor;

namespace SeataNet.Core.Cluster
{
    /// <summary>
    /// 集群管理器接口
    /// </summary>
    public interface IClusterManager
    {
        /// <summary>
        /// 启动集群管理器
        /// </summary>
        Task StartAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 停止集群管理器
        /// </summary>
        Task StopAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// 获取集群节点列表
        /// </summary>
        /// <returns>集群节点列表</returns>
        List<ClusterNode> GetClusterNodes();

        /// <summary>
        /// 获取当前节点
        /// </summary>
        /// <returns>当前节点</returns>
        ClusterNode GetCurrentNode();

        /// <summary>
        /// 获取主节点
        /// </summary>
        /// <returns>主节点</returns>
        ClusterNode? GetMasterNode();

        /// <summary>
        /// 检查节点是否可用
        /// </summary>
        /// <param name="nodeId">节点ID</param>
        /// <returns>是否可用</returns>
        bool IsNodeAvailable(string nodeId);

        /// <summary>
        /// 获取可用节点列表
        /// </summary>
        /// <returns>可用节点列表</returns>
        List<ClusterNode> GetAvailableNodes();

        /// <summary>
        /// 选举主节点
        /// </summary>
        /// <returns>主节点</returns>
        Task<ClusterNode?> ElectMasterAsync();

        /// <summary>
        /// 注册节点
        /// </summary>
        /// <param name="node">节点信息</param>
        /// <returns>注册结果</returns>
        Task<bool> RegisterNodeAsync(ClusterNode node);

        /// <summary>
        /// 注销节点
        /// </summary>
        /// <param name="nodeId">节点ID</param>
        /// <returns>注销结果</returns>
        Task<bool> UnregisterNodeAsync(string nodeId);

        /// <summary>
        /// 发送心跳
        /// </summary>
        /// <param name="nodeId">节点ID</param>
        /// <returns>心跳结果</returns>
        Task<bool> SendHeartbeatAsync(string nodeId);

        /// <summary>
        /// 获取集群统计信息
        /// </summary>
        /// <returns>集群统计信息</returns>
        ClusterStatistics GetClusterStatistics();
    }

    /// <summary>
    /// 默认集群管理器实现
    /// </summary>
    public class DefaultClusterManager : IClusterManager, IDisposable
    {
        private readonly ILogger<DefaultClusterManager> _logger;
        private readonly IOptionsMonitor<ClusterConfiguration> _configuration;
        private readonly IRpcClient _rpcClient;
        private readonly ITransactionMonitor _transactionMonitor;

        private readonly ConcurrentDictionary<string, ClusterNode> _clusterNodes;
        private ClusterNode _currentNode;
        private ClusterNode? _masterNode;
        private Timer? _heartbeatTimer;
        private Timer? _healthCheckTimer;
        private Timer? _electionTimer;
        private bool _disposed = false;
        private bool _isRunning = false;
        private readonly object _electionLock = new object();
        private readonly object _masterLock = new object();

        public DefaultClusterManager(
            ILogger<DefaultClusterManager> logger,
            IOptionsMonitor<ClusterConfiguration> configuration,
            IRpcClient rpcClient,
            ITransactionMonitor transactionMonitor)
        {
            _logger = logger;
            _configuration = configuration;
            _rpcClient = rpcClient;
            _transactionMonitor = transactionMonitor;
            _clusterNodes = new ConcurrentDictionary<string, ClusterNode>();

            // 初始化当前节点
            _currentNode = CreateCurrentNode();
        }

        public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            if (_isRunning)
            {
                _logger.LogDebug("Cluster manager is already running");
                return;
            }

            _isRunning = true;
            _logger.LogInformation("Starting cluster manager, Node ID: {NodeId}", _currentNode.NodeId);

            var config = _configuration.CurrentValue;

            // 注册当前节点
            _clusterNodes.TryAdd(_currentNode.NodeId, _currentNode);

            // 启动心跳定时器
            _heartbeatTimer = new Timer(
                async _ => await SendHeartbeatToAllNodesAsync(),
                null,
                TimeSpan.FromSeconds(config.HeartbeatIntervalSeconds),
                TimeSpan.FromSeconds(config.HeartbeatIntervalSeconds));

            // 启动健康检查定时器
            _healthCheckTimer = new Timer(
                async _ => await CheckNodeHealthAsync(),
                null,
                TimeSpan.FromSeconds(config.HealthCheckIntervalSeconds),
                TimeSpan.FromSeconds(config.HealthCheckIntervalSeconds));

            // 启动选举定时器
            _electionTimer = new Timer(
                async _ => await CheckMasterNodeAsync(),
                null,
                TimeSpan.FromSeconds(config.ElectionCheckIntervalSeconds),
                TimeSpan.FromSeconds(config.ElectionCheckIntervalSeconds));

            // 如果是单节点模式，直接设置为主节点
            if (config.EnableSingleNodeMode)
            {
                lock (_masterLock)
                {
                    _masterNode = _currentNode;
                    _masterNode.IsMaster = true;
                    _currentNode.IsMaster = true;
                }
                _logger.LogInformation("Single node mode enabled, current node is master");
            }
            else
            {
                // 尝试发现其他节点
                await DiscoverNodesAsync(cancellationToken);

                // 如果没有主节点，进行选举
                if (_masterNode == null)
                {
                    await ElectMasterAsync();
                }
            }

            _logger.LogInformation("Cluster manager started successfully");
        }

        public async Task StopAsync(CancellationToken cancellationToken = default)
        {
            if (!_isRunning)
            {
                _logger.LogDebug("Cluster manager is not running");
                return;
            }

            _isRunning = false;
            _logger.LogInformation("Stopping cluster manager");

            // 注销当前节点
            if (_clusterNodes.ContainsKey(_currentNode.NodeId))
            {
                await UnregisterNodeAsync(_currentNode.NodeId);
            }

            // 停止定时器
            _heartbeatTimer?.Dispose();
            _healthCheckTimer?.Dispose();
            _electionTimer?.Dispose();

            _logger.LogInformation("Cluster manager stopped");
        }

        public List<ClusterNode> GetClusterNodes()
        {
            return _clusterNodes.Values.ToList();
        }

        public ClusterNode GetCurrentNode()
        {
            return _currentNode;
        }

        public ClusterNode? GetMasterNode()
        {
            lock (_masterLock)
            {
                return _masterNode;
            }
        }

        public bool IsNodeAvailable(string nodeId)
        {
            if (_clusterNodes.TryGetValue(nodeId, out var node))
            {
                return node.Status == NodeStatus.Available && node.IsAlive;
            }
            return false;
        }

        public List<ClusterNode> GetAvailableNodes()
        {
            return _clusterNodes.Values
                .Where(n => n.Status == NodeStatus.Available && n.IsAlive)
                .ToList();
        }

        public async Task<ClusterNode?> ElectMasterAsync()
        {
            lock (_electionLock)
            {
                if (_masterNode != null && _masterNode.IsAlive)
                {
                    return _masterNode;
                }
            }

            _logger.LogInformation("Starting master election");

            var availableNodes = GetAvailableNodes();
            if (!availableNodes.Any())
            {
                _logger.LogWarning("No available nodes for master election");
                return null;
            }

            // 根据节点优先级和ID进行排序，选择第一个作为主节点
            var masterCandidate = availableNodes
                .OrderByDescending(n => n.Priority)
                .ThenBy(n => n.NodeId)
                .First();

            // 通知所有节点选举结果
            var electionTasks = availableNodes.Select(async node =>
            {
                try
                {
                    if (node.NodeId == _currentNode.NodeId)
                    {
                        // 当前节点成为主节点
                        lock (_masterLock)
                        {
                            _masterNode = _currentNode;
                            _masterNode.IsMaster = true;
                            _currentNode.IsMaster = true;
                        }
                        _logger.LogInformation("Current node elected as master");
                    }
                    else
                    {
                        // 通知其他节点选举结果
                        await NotifyMasterElectionAsync(node, masterCandidate);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error notifying node {NodeId} about master election", node.NodeId);
                }
            });

            await Task.WhenAll(electionTasks);

            _logger.LogInformation("Master election completed, Master Node ID: {NodeId}", masterCandidate.NodeId);

            lock (_masterLock)
            {
                return _masterNode;
            }
        }

        public async Task<bool> RegisterNodeAsync(ClusterNode node)
        {
            try
            {
                _logger.LogDebug("Registering node, Node ID: {NodeId}", node.NodeId);

                node.LastHeartbeat = DateTime.UtcNow;
                node.IsAlive = true;
                node.Status = NodeStatus.Available;

                _clusterNodes.TryAdd(node.NodeId, node);

                // 如果当前节点是主节点，通知所有其他节点
                var masterNode = GetMasterNode();
                if (masterNode != null && masterNode.NodeId == _currentNode.NodeId)
                {
                    await NotifyNodeRegistrationAsync(node);
                }

                _logger.LogDebug("Node registered successfully, Node ID: {NodeId}", node.NodeId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error registering node, Node ID: {NodeId}", node.NodeId);
                return false;
            }
        }

        public async Task<bool> UnregisterNodeAsync(string nodeId)
        {
            try
            {
                _logger.LogDebug("Unregistering node, Node ID: {NodeId}", nodeId);

                if (_clusterNodes.TryRemove(nodeId, out var node))
                {
                    // 如果注销的是主节点，触发重新选举
                    if (_masterNode?.NodeId == nodeId)
                    {
                        lock (_masterLock)
                        {
                            _masterNode = null;
                        }
                        await ElectMasterAsync();
                    }

                    // 如果当前节点是主节点，通知所有其他节点
                    var masterNode = GetMasterNode();
                    if (masterNode != null && masterNode.NodeId == _currentNode.NodeId)
                    {
                        await NotifyNodeUnregistrationAsync(node);
                    }

                    _logger.LogDebug("Node unregistered successfully, Node ID: {NodeId}", nodeId);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error unregistering node, Node ID: {NodeId}", nodeId);
                return false;
            }
        }

        public async Task<bool> SendHeartbeatAsync(string nodeId)
        {
            try
            {
                if (_clusterNodes.TryGetValue(nodeId, out var node))
                {
                    var heartbeat = new HeartbeatMessage
                    {
                        NodeId = _currentNode.NodeId,
                        Timestamp = DateTime.UtcNow,
                        Status = _currentNode.Status,
                        IsMaster = _currentNode.IsMaster
                    };

                    // 发送心跳消息
                    await _rpcClient.SendMessageAsync(node.Address, heartbeat);

                    _logger.LogDebug("Heartbeat sent to node {NodeId}", nodeId);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending heartbeat to node {NodeId}", nodeId);
                return false;
            }
        }

        public ClusterStatistics GetClusterStatistics()
        {
            var nodes = _clusterNodes.Values.ToList();
            var availableNodes = GetAvailableNodes();

            return new ClusterStatistics
            {
                TotalNodes = nodes.Count,
                AvailableNodes = availableNodes.Count,
                MasterNodeId = _masterNode?.NodeId,
                CurrentNodeId = _currentNode.NodeId,
                IsCurrentNodeMaster = _currentNode.IsMaster,
                LastElectionTime = _masterNode?.ElectedTime,
                ClusterStartTime = _currentNode.RegisterTime,
                AverageResponseTime = CalculateAverageResponseTime(nodes),
                TotalTransactions = GetTotalTransactions(),
                ActiveTransactions = GetActiveTransactions()
            };
        }

        /// <summary>
        /// 创建当前节点
        /// </summary>
        private ClusterNode CreateCurrentNode()
        {
            var config = _configuration.CurrentValue;
            var hostName = Dns.GetHostName();
            var hostEntry = Dns.GetHostEntry(hostName);
            var ipAddress = hostEntry.AddressList
                .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString() ?? "127.0.0.1";

            return new ClusterNode
            {
                NodeId = $"{hostName}_{Guid.NewGuid():N}",
                HostName = hostName,
                Address = $"{ipAddress}:{config.Port}",
                Port = config.Port,
                Status = NodeStatus.Available,
                IsAlive = true,
                IsMaster = false,
                Priority = config.NodePriority,
                RegisterTime = DateTime.UtcNow,
                LastHeartbeat = DateTime.UtcNow,
                ElectedTime = null,
                Version = "1.0.0"
            };
        }

        /// <summary>
        /// 发现节点
        /// </summary>
        private async Task DiscoverNodesAsync(CancellationToken cancellationToken)
        {
            try
            {
                var config = _configuration.CurrentValue;
                if (!config.DiscoveryEnabled)
                {
                    return;
                }

                _logger.LogDebug("Discovering cluster nodes");

                // 从配置中获取已知节点
                foreach (var nodeAddress in config.KnownNodes)
                {
                    try
                    {
                        // 发送发现请求
                        var discoveryRequest = new NodeDiscoveryRequest
                        {
                            NodeId = _currentNode.NodeId,
                            Address = _currentNode.Address
                        };

                        var response = await _rpcClient.SendMessageAsync<NodeDiscoveryResponse>(nodeAddress, discoveryRequest);
                        if (response != null && response.Node != null)
                        {
                            await RegisterNodeAsync(response.Node);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error discovering node at {NodeAddress}", nodeAddress);
                    }
                }

                _logger.LogDebug("Node discovery completed");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in node discovery");
            }
        }

        /// <summary>
        /// 向所有节点发送心跳
        /// </summary>
        private async Task SendHeartbeatToAllNodesAsync()
        {
            try
            {
                var nodes = _clusterNodes.Values
                    .Where(n => n.NodeId != _currentNode.NodeId)
                    .ToList();

                var heartbeatTasks = nodes.Select(async node =>
                {
                    try
                    {
                        await SendHeartbeatAsync(node.NodeId);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error sending heartbeat to node {NodeId}", node.NodeId);
                    }
                });

                await Task.WhenAll(heartbeatTasks);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending heartbeats to all nodes");
            }
        }

        /// <summary>
        /// 检查节点健康状态
        /// </summary>
        private async Task CheckNodeHealthAsync()
        {
            try
            {
                var config = _configuration.CurrentValue;
                var now = DateTime.UtcNow;
                var timeout = TimeSpan.FromSeconds(config.NodeTimeoutSeconds);

                foreach (var node in _clusterNodes.Values)
                {
                    if (node.NodeId == _currentNode.NodeId)
                    {
                        continue;
                    }

                    // 检查节点是否超时
                    if (now - node.LastHeartbeat > timeout)
                    {
                        if (node.IsAlive)
                        {
                            _logger.LogWarning("Node {NodeId} is not responding, marking as unavailable", node.NodeId);
                            node.IsAlive = false;
                            node.Status = NodeStatus.Unavailable;

                            // 如果是主节点超时，触发重新选举
                            if (_masterNode?.NodeId == node.NodeId)
                            {
                                lock (_masterLock)
                                {
                                    _masterNode = null;
                                }
                                await ElectMasterAsync();
                            }
                        }
                    }
                    else if (!node.IsAlive && node.Status == NodeStatus.Unavailable)
                    {
                        _logger.LogInformation("Node {NodeId} is responding again, marking as available", node.NodeId);
                        node.IsAlive = true;
                        node.Status = NodeStatus.Available;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error checking node health");
            }
        }

        /// <summary>
        /// 检查主节点状态
        /// </summary>
        private async Task CheckMasterNodeAsync()
        {
            try
            {
                if (_masterNode == null)
                {
                    await ElectMasterAsync();
                    return;
                }

                // 如果当前节点是主节点，检查是否仍然是主节点
                if (_masterNode.NodeId == _currentNode.NodeId)
                {
                    // 当前节点是主节点，无需检查
                    return;
                }

                // 检查主节点是否仍然可用
                if (!IsNodeAvailable(_masterNode.NodeId))
                {
                    _logger.LogWarning("Master node {NodeId} is unavailable, triggering re-election", _masterNode.NodeId);
                    lock (_masterLock)
                    {
                        _masterNode = null;
                    }
                    await ElectMasterAsync();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error checking master node");
            }
        }

        /// <summary>
        /// 通知节点主选举结果
        /// </summary>
        private async Task NotifyMasterElectionAsync(ClusterNode node, ClusterNode masterNode)
        {
            try
            {
                var notification = new MasterElectionNotification
                {
                    MasterNodeId = masterNode.NodeId,
                    MasterNodeAddress = masterNode.Address,
                    ElectionTime = DateTime.UtcNow
                };

                await _rpcClient.SendMessageAsync(node.Address, notification);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error notifying node {NodeId} about master election", node.NodeId);
            }
        }

        /// <summary>
        /// 通知节点注册
        /// </summary>
        private async Task NotifyNodeRegistrationAsync(ClusterNode node)
        {
            try
            {
                var notification = new NodeRegistrationNotification
                {
                    Node = node,
                    Timestamp = DateTime.UtcNow
                };

                var nodes = _clusterNodes.Values
                    .Where(n => n.NodeId != _currentNode.NodeId && n.NodeId != node.NodeId)
                    .ToList();

                var notificationTasks = nodes.Select(async n =>
                {
                    try
                    {
                        await _rpcClient.SendMessageAsync(n.Address, notification);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error notifying node {NodeId} about node registration", n.NodeId);
                    }
                });

                await Task.WhenAll(notificationTasks);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error notifying nodes about node registration");
            }
        }

        /// <summary>
        /// 通知节点注销
        /// </summary>
        private async Task NotifyNodeUnregistrationAsync(ClusterNode node)
        {
            try
            {
                var notification = new NodeUnregistrationNotification
                {
                    NodeId = node.NodeId,
                    Timestamp = DateTime.UtcNow
                };

                var nodes = _clusterNodes.Values
                    .Where(n => n.NodeId != _currentNode.NodeId && n.NodeId != node.NodeId)
                    .ToList();

                var notificationTasks = nodes.Select(async n =>
                {
                    try
                    {
                        await _rpcClient.SendMessageAsync(n.Address, notification);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error notifying node {NodeId} about node unregistration", n.NodeId);
                    }
                });

                await Task.WhenAll(notificationTasks);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error notifying nodes about node unregistration");
            }
        }

        /// <summary>
        /// 计算平均响应时间
        /// </summary>
        private double CalculateAverageResponseTime(List<ClusterNode> nodes)
        {
            if (!nodes.Any())
            {
                return 0;
            }

            return nodes.Average(n => n.AverageResponseTime);
        }

        /// <summary>
        /// 获取总事务数
        /// </summary>
        private long GetTotalTransactions()
        {
            try
            {
                var stats = _transactionMonitor.GetTransactionStatistics(
                    DateTime.UtcNow.AddDays(-1), DateTime.UtcNow);
                return stats.TotalTransactions;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取活跃事务数
        /// </summary>
        private long GetActiveTransactions()
        {
            try
            {
                return _transactionMonitor.GetActiveTransactions().Count;
            }
            catch
            {
                return 0;
            }
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                _heartbeatTimer?.Dispose();
                _healthCheckTimer?.Dispose();
                _electionTimer?.Dispose();
                _disposed = true;
            }
        }
    }

    /// <summary>
    /// 集群节点
    /// </summary>
    public class ClusterNode
    {
        /// <summary>
        /// 节点ID
        /// </summary>
        public string NodeId { get; set; } = string.Empty;

        /// <summary>
        /// 主机名
        /// </summary>
        public string HostName { get; set; } = string.Empty;

        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; } = string.Empty;

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public NodeStatus Status { get; set; }

        /// <summary>
        /// 是否存活
        /// </summary>
        public bool IsAlive { get; set; }

        /// <summary>
        /// 是否为主节点
        /// </summary>
        public bool IsMaster { get; set; }

        /// <summary>
        /// 优先级
        /// </summary>
        public int Priority { get; set; }

        /// <summary>
        /// 注册时间
        /// </summary>
        public DateTime RegisterTime { get; set; }

        /// <summary>
        /// 最后心跳时间
        /// </summary>
        public DateTime LastHeartbeat { get; set; }

        /// <summary>
        /// 选举时间
        /// </summary>
        public DateTime? ElectedTime { get; set; }

        /// <summary>
        /// 版本
        /// </summary>
        public string Version { get; set; } = string.Empty;

        /// <summary>
        /// 平均响应时间（毫秒）
        /// </summary>
        public double AverageResponseTime { get; set; }
    }

    /// <summary>
    /// 节点状态
    /// </summary>
    public enum NodeStatus
    {
        /// <summary>
        /// 可用
        /// </summary>
        Available,

        /// <summary>
        /// 不可用
        /// </summary>
        Unavailable,

        /// <summary>
        /// 维护中
        /// </summary>
        Maintenance
    }

    /// <summary>
    /// 集群统计信息
    /// </summary>
    public class ClusterStatistics
    {
        /// <summary>
        /// 总节点数
        /// </summary>
        public int TotalNodes { get; set; }

        /// <summary>
        /// 可用节点数
        /// </summary>
        public int AvailableNodes { get; set; }

        /// <summary>
        /// 主节点ID
        /// </summary>
        public string? MasterNodeId { get; set; }

        /// <summary>
        /// 当前节点ID
        /// </summary>
        public string CurrentNodeId { get; set; } = string.Empty;

        /// <summary>
        /// 当前节点是否为主节点
        /// </summary>
        public bool IsCurrentNodeMaster { get; set; }

        /// <summary>
        /// 最后选举时间
        /// </summary>
        public DateTime? LastElectionTime { get; set; }

        /// <summary>
        /// 集群启动时间
        /// </summary>
        public DateTime ClusterStartTime { get; set; }

        /// <summary>
        /// 平均响应时间（毫秒）
        /// </summary>
        public double AverageResponseTime { get; set; }

        /// <summary>
        /// 总事务数
        /// </summary>
        public long TotalTransactions { get; set; }

        /// <summary>
        /// 活跃事务数
        /// </summary>
        public long ActiveTransactions { get; set; }
    }

    /// <summary>
    /// 心跳消息
    /// </summary>
    public class HeartbeatMessage
    {
        /// <summary>
        /// 节点ID
        /// </summary>
        public string NodeId { get; set; } = string.Empty;

        /// <summary>
        /// 时间戳
        /// </summary>
        public DateTime Timestamp { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public NodeStatus Status { get; set; }

        /// <summary>
        /// 是否为主节点
        /// </summary>
        public bool IsMaster { get; set; }
    }

    /// <summary>
    /// 节点发现请求
    /// </summary>
    public class NodeDiscoveryRequest
    {
        /// <summary>
        /// 节点ID
        /// </summary>
        public string NodeId { get; set; } = string.Empty;

        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; } = string.Empty;
    }

    /// <summary>
    /// 节点发现响应
    /// </summary>
    public class NodeDiscoveryResponse
    {
        /// <summary>
        /// 节点信息
        /// </summary>
        public ClusterNode? Node { get; set; }
    }

    /// <summary>
    /// 主选举通知
    /// </summary>
    public class MasterElectionNotification
    {
        /// <summary>
        /// 主节点ID
        /// </summary>
        public string MasterNodeId { get; set; } = string.Empty;

        /// <summary>
        /// 主节点地址
        /// </summary>
        public string MasterNodeAddress { get; set; } = string.Empty;

        /// <summary>
        /// 选举时间
        /// </summary>
        public DateTime ElectionTime { get; set; }
    }

    /// <summary>
    /// 节点注册通知
    /// </summary>
    public class NodeRegistrationNotification
    {
        /// <summary>
        /// 节点信息
        /// </summary>
        public ClusterNode Node { get; set; } = new ClusterNode();

        /// <summary>
        /// 时间戳
        /// </summary>
        public DateTime Timestamp { get; set; }
    }

    /// <summary>
    /// 节点注销通知
    /// </summary>
    public class NodeUnregistrationNotification
    {
        /// <summary>
        /// 节点ID
        /// </summary>
        public string NodeId { get; set; } = string.Empty;

        /// <summary>
        /// 时间戳
        /// </summary>
        public DateTime Timestamp { get; set; }
    }
}